import { randomUploadFileName, getValueFromXml, isHasOwnProperty } from '@/plugins/utils'
import { CONTROL_TYPES } from '@/common/const-wb'
import crc32 from '@/components/utils/crc/crc32'

const fileUploadUrl = 'https://sinastorage.com/file.hd.xxx.com/';
const fileUploadS3Url_ = 'https://picupload.xxx.com/interface/upload.php';

export const canvasUploadImg = {
  methods: {
    showAlert(content) {
      this.$dialog.alert({
        title: '',
        message: content,
      })
    },
    setUploadParams(blobObj, base64, pushCompId, fileName) {
      let unit8Array = this.base64ToUInt8Array(base64);
      let this_ = this;
      let url = fileUploadS3Url_ + "?ent=miniblog&appid=" + this_.appid + "&uid=" + this_.userInfo.uid + "&file_source=67&cs=" + crc32(unit8Array);
      // let reader = new FileReader();
      // reader.onload = function() {
        let option = {
          action: url,
          onSuccess: (response) => {
            if(!response.ret){
              this_.showAlert(response.errno);
              return
            }
            let data = response.pic;
            let pic_id = data.pid
            let original_pic = base64
            
            this_.onSuccessCb(pic_id, original_pic, pushCompId, fileName)
          },
          onError: (err) => {
            this_.showAlert(err);
          },
          type: 'image',
          data: blobObj,
          withCredentials: true,
          headers: {"Content-Type": "multipart/form-data"}
        }
        this_.upload(option);
      // }
      // reader.readAsArrayBuffer(blobObj);
    },
    onSuccessCb(pic_id, original_pic, pushCompId, fileName){
      if(pushCompId){
        this.canvasImgComponentMap[pushCompId] = pushCompId;
        let picItem = { pic_id, pic_url: original_pic }
        this.$store.commit("updatePushPicItem", { id: pushCompId, controlId: CONTROL_TYPES.wb_push, picItem, fileName })
      }else if(this.item.events[EVENT_HOVER_TYPES.push.type]){
        this.canvasImgComponentMap[pushCompId] = pushCompId;
        let picItem = { pic_id, pic_url: original_pic }
        this.$store.commit("updatePushPicItem", { id: this.item.id, controlId: CONTROL_TYPES.wb_push, picItem, fileName })
      }else if(this.item.events[EVENT_HOVER_TYPES.openPush.type]){
        let cameraItem = {
          thumbnail: original_pic,
          original: original_pic,
          pid: pic_id,
        }
        let pics = [cameraItem]
        this.$store.commit("updateFrontData", { id: this.item.id, data: {pics} })
      }
      //从camara过来的，需要发事件继续执行组件剩余的事件
      // this.isPostWbEventOrCommonEvents({ loadEvent: null, e: null })
    },
    uploadFormImgToServer(blobObj, suffix, cbs, cbf){
      let filename =  randomUploadFileName(this.siteInfo.id) + "." + suffix;
      let fileUploadData = _.cloneDeep(this.fileUploadData);
      fileUploadData.key += filename;
      let option = {
        action: fileUploadUrl,
        onSuccess: (response) => {
          let url = getValueFromXml(response);
          url = _.replace(url, 'http', 'https');
          url = _.replace(url, 'file', 'static');
          url = _.replace(url, '.s3.sinaapp.com', '');
          
          if(cbs){
            cbs(url);
          }
        },
        onError: () => {
          if(cbf){
            cbf();
          }
        },
        data: fileUploadData,
        fileKey: "file",
        file: blobObj,
      }
      this.upload(option);
    },
    fileToBlob(dataURL, suffix, cbs, cbf){
      let blob = this.dataURLToBlob(dataURL);
      this.uploadFormImgToServer(blob, suffix, cbs, cbf);
    },
    base64ToUInt8Array(base64){
      let BASE64_MARKER = ';base64,';
      let raw;
      let parts;
      parts = base64.split(BASE64_MARKER);
      raw = window.atob(parts[1]);
      let rawLength = raw.length;
      var uInt8Array = new Uint8Array(rawLength);
      for (var i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
      }
      return uInt8Array
    },
    dataURLToBlob(dataURL) {
      let BASE64_MARKER = ';base64,';
      let raw;
      let contentType;
      let parts;
      if (dataURL.indexOf(BASE64_MARKER) == -1) {
        parts = dataURL.split(',');
        contentType = parts[0].split(':')[1];
        raw = decodeURIComponent(parts[1]);

        return new Blob([raw], { type: contentType });
      }
      parts = dataURL.split(BASE64_MARKER);
      contentType = parts[0].split(':')[1];
      raw = window.atob(parts[1]);
      let rawLength = raw.length;
      var uInt8Array = new Uint8Array(rawLength);
      for (var i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
      }
      return new Blob([uInt8Array], { type: contentType });
    },
    upload(option){
      var xhr = new XMLHttpRequest();
      if(option.withCredentials){
        xhr.withCredentials = true;
      }
      var action = option.action;
      let type = option.type ? option.type : 'formdata';
      let data = null;
      if(type == 'image'){
        data = option.data
      }else{
        var formData = new FormData();
        if (option.data) {
          Object.keys(option.data).forEach((key) => {
            formData.append(key, option.data[key]);
          });
        }
        formData.append(option.fileKey, option.file);
        data = formData;
      }
      xhr.onerror = (e) => {
        option.onError(e);
      };
      xhr.onload = () => {
        if (xhr.status < 200 || xhr.status >= 300) {
          return option.onError(this.getError(action, option, xhr));
        }
        option.onSuccess(this.getBody(xhr));
      };
      xhr.open('post', action, true);
      var headers = option.headers || {};
      for (var key in headers) {
        if (isHasOwnProperty(headers, key) && headers[key] !== null) {
          xhr.setRequestHeader(key, headers[key]);
        }
      }
      xhr.send(data);
      return xhr;

    },
    getBody(xhr) {
      let text = xhr.responseText || xhr.response;
      if (!text) {
        return text;
      }
      try {
        return JSON.parse(text);
      } catch (e) {
        return text;
      }
    },
    getError(action, option, xhr) {
      let msg = void 0;
      if (xhr.response) {
        msg = '' + (xhr.response.error || xhr.response);
      } else if (xhr.responseText) {
        msg = '' + xhr.responseText;
      } else {
        msg = 'fail to post ' + action + ' ' + xhr.status;
      }
      let err = new Error(msg);
      err.status = xhr.status;
      err.method = 'post';
      err.url = action;
      return err;
    },
  }
}